/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import it.master.cloud.carsharing.dbmanager.DBManager;
import it.master.cloud.carsharing.domain.RouteJSON;
import it.master.cloud.carsharing.domain.Routes;
import it.master.cloud.carsharing.webservice.WebServices;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author cloud
 */
public class RegistrationServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        if (request.getParameter("registration") != null) {
            String user = request.getParameter("uname");
            String pwd = request.getParameter("pass");
            String fname = request.getParameter("fname");
            String lname = request.getParameter("lname");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");

            String resultRegistration;

            WebServices service = new WebServices();
            resultRegistration = service.register(fname, lname, user, pwd, email, phone);

            if (resultRegistration.equals("success")) {
                response.sendRedirect("login.jsp");
            } else {
                response.sendRedirect("index.jsp");
            }
        } else if (request.getParameter("controlUsername") != null) {

            String username = request.getParameter("username");

            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {

                String res = DBManager.controlLogin(username);
                out.println(res);
            } finally {
                out.close();
            }

        } else if (request.getParameter("login") != null) {

            String username = request.getParameter("uname");
            String password = request.getParameter("pass");

            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            
            String res = DBManager.controlLogin(username, password);
            String userId = DBManager.getUserId(username, password);
            
            if (res.equals("success")) {
                HttpSession s = request.getSession();
                s.setAttribute("username", username);
                s.setAttribute("userId", userId);
                response.sendRedirect("insertRoute.jsp");
            } else {
                response.sendRedirect("login.jsp?loginError=1");
            }
        

        } else if (request.getParameter("insert") != null) {
            
            HttpSession s = request.getSession();
            Integer userId = Integer.parseInt(s.getAttribute("userId").toString());
            String address_from = request.getParameter("address_from");
            String address_to = request.getParameter("address_to");
            String start_hour = request.getParameter("start_hour");
            String arrive_hour = request.getParameter("arrive_hour");
            Integer seats = Integer.parseInt(request.getParameter("seats"));
            
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            
            WebServices service = new WebServices();
            String result = service.insertRoute(userId, address_from, address_to, start_hour, arrive_hour, seats);
                
                if (result.equals("success"))
                {
                    response.sendRedirect("insertRoute.jsp?insertRoute=1");
                }
                else
                {
                    response.sendRedirect("insertRoute.jsp?insertRoute=0");
                }
        } else if (request.getParameter("searchRoute") != null) {

            String startHour = request.getParameter("startHour");
            String arriveHour = request.getParameter("arriveHour");
            String addressFrom = request.getParameter("addressFrom");
            String addressTo = request.getParameter("addressTo");
            Integer seats = null;
            if (!request.getParameter("seats").equals(""))
            {
                seats = Integer.valueOf(request.getParameter("seats"));
            }

            List<RouteJSON> routes = new ArrayList<>();

            WebServices service = new WebServices();
            routes = service.getRoutes(startHour, arriveHour, addressFrom, addressTo, seats);

            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();

            String result = "<!DOCTYPE html><html><head>\n" +
"        <title>Cerca altri utenti per il tuo tragitto</title>\n" +
"        <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n" +
"        <meta name=\"description\" content=\"\" />\n" +
"        <meta name=\"keywords\" content=\"\" />\n" +
"        <link href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,700,500,900' rel='stylesheet' type='text/css'>\n" +
"        <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js\"></script>\n" +
"        <script src=\"js/skel.min.js\"></script>\n" +
"        <script src=\"js/skel-panels.min.js\"></script>\n" +
"        <script src=\"js/init.js\"></script>\n" +
"        <script src=\"js/jquery-1.9.1.js\"></script>\n" +
"        <noscript>\n" +
"        <link rel=\"stylesheet\" href=\"css/skel-noscript.css\" />\n" +
"        <link rel=\"stylesheet\" href=\"css/style.css\" />\n" +
"        <link rel=\"stylesheet\" href=\"css/style-desktop.css\" />\n" +
"        </noscript>\n" +
"    </head><body>"
                    + "<!-- Header -->\n" +
"        <div id=\"header\">\n" +
"            <div id=\"nav-wrapper\"> \n" +
"                <!-- Nav -->\n" +
"                <nav id=\"nav\">\n" +
"                    <ul>\n" +
"                        <li><a href=\"index.html\">Homepage</a></li>\n" +
"                        <li class=\"active\"><a href=\"registration.jsp\">Registrazione</a></li>\n" +
"                        <li><a href=\"insertRoute.jsp\">Inserimento</a></li>\n" +
"                        <li><a href=\"searchRoute.jsp\">Ricerca</a></li>\n" +
"                    </ul>\n" +
"                </nav>\n" +
"            </div>\n" +
"            <div class=\"container\"> \n" +
"\n" +
"                <!-- Logo -->\n" +
"                <div id=\"logo\">\n" +
"                    <h1><a href=\"#\">Car Sharing</a></h1>\n" +
"                </div>\n" +
"            </div>\n" +
"        </div>\n" +
"        <!-- Header --> \n" +
"\n" +
"        <!-- Main -->\n" +
"        <div id=\"main\">\n" +
"            <div class=\"container\">\n" +
"                <div class=\"row\">\n" +
"\n" +
"                    <!-- Sidebar -->\n" +
"                    <div id=\"sidebar\" class=\"4u\">\n" +
"                        <section>\n" +
"                            <header>\n" +
"                                <h2><a href=\"registration.jsp\">Registrazione</a></h2>\n" +
"                            </header>\n" +
"                        </section>\n" +
"                        <section>\n" +
"                            <header>\n" +
"                                <h2><a href=\"login.jsp\">Login</a></h2>\n" +
"                            </header>\n" +
"                        </section>\n" +
"                        <section>\n" +
"                            <header>\n" +
"                                <h2><a href=\"insertRoute.jsp\">Inserimento</a></h2>\n" +
"                            </header>\n" +
"                        </section>\n" +
"                        <section>\n" +
"                            <header>\n" +
"                                <h2><a href=\"searchRoute.jsp\">Ricerca</a></h2>\n" +
"                            </header>\n" +
"                        </section>\n" +
"                    </div>\n" +
"\n" +
"                    <!-- Content -->\n" +
"                    <div id=\"content\" class=\"8u skel-cell-important\">\n" +
"                        <section>\n" +
"                            <header>\n" +
"                                <h2>Risultati della ricerca</h2>\n" +
"                            </header>\n" +
"<table class='searchResults'><tr><th>Nome</th><th>Cognome</th><th>Mail</th><th>Telefono</th><th>Luogo di Partenza</th><th>Luogo di Arrivo</th><th>Ora di Partenza</th><th>Ora di Arrivo</th><th>Posti Disponibili</th></tr>";

            try {
                for (RouteJSON route : routes) {

                    result += "<tr>";

                    result += "<td>" + route.getName() + "</td>";
                    result += "<td>" + route.getSurname() + "</td>";
                    result += "<td>" + route.getMail() + "</td>";
                    result += "<td>" + route.getPhone() + "</td>";
                    result += "<td>" + route.getAddressFrom() + "</td>";
                    result += "<td>" + route.getAddressTo() + "</td>";
                    result += "<td>" + route.getStartHour() + "</td>";
                    result += "<td>" + route.getArriveHour() + "</td>";
                    result += "<td>" + route.getSeats() + "</td>";

                    result += "</tr>";
                }
                
                result += "</table></section></div></div></div></div><!-- Tweet -->\n" +
"        <div id=\"tweet\">\n" +
"            <div class=\"container\">\n" +
"                <section>\n" +
"                    <blockquote>La tua applicazione per risparmiare benzina</blockquote>\n" +
"                </section>\n" +
"            </div>\n" +
"\n" +
"        </div>\n" +
"\n" +
"        <!-- Copyright -->\n" +
"        <div id=\"copyright\">\n" +
"            <div class=\"container\">\n" +
"                Design: <a href=\"http://templated.co\">TEMPLATED</a> Images: <a href=\"http://unsplash.com\">Unsplash</a> (<a href=\"http://unsplash.com/cc0\">CC0</a>)\n" +
"            </div>\n" +
"        </div></body></html>";
                out.println(result);
            } finally {
                out.close();
            }
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
